package com.geek.javase.ch15.work.banksync;

/*
 *@author wangpeng
 *2025/10/31 20:19
 *@description TODO
 */

public class Account {

    private String bank;
    private double balance;
    public Account(String bank, double balance) {
        this.bank = bank;
        this.balance = balance;
    }
    //存款
    public void deposit(double money) {
        synchronized (this) {
            // 如果余额大于0，则存款线程等待（避免重复存款）
            while(balance>0){
                System.out.println(Thread.currentThread().getName()+"余额充足，等待");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            balance+=money;
            System.out.println(Thread.currentThread().getName()+"存款成功，余额为："+balance);
            // 唤醒所有等待的线程
            notifyAll();
        }
    }
    //取款
    public void withdraw(double money) {
        synchronized (this) {
            // 如果余额不足，则取款线程等待（避免透支）
            while(balance<money){
                System.out.println(Thread.currentThread().getName()+"取款失败，余额不足,等待");
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            balance-=money;
            System.out.println(Thread.currentThread().getName()+"取款成功，余额为："+balance);
            // 唤醒所有等待的线程
            notifyAll();
        }
    }
}

